import { defineStore } from 'pinia'
import { ref } from 'vue'
import { computed } from 'vue'
//用户信息结构
const initUserInfo = {
  avatar: '',
  birthDate: '',
  coinBalance: 0,
  email: '',
  gender: 0,
  loginTime: '',
  memberLevel: 0,
  nickname: '',
  openId: '',
  phoneNumber: '',
  signature: '',
  userId: ''
}
export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')

  //从localStore中解析用户信息
  const loaderUserInfo = () => {
    try {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {

        return { ...initUserInfo, ...JSON.parse(userInfoStr) }
      }
    } catch (error) {
      //解析错误
      console.log(error)
    }
    return { ...initUserInfo }
  }

  const userInfo = ref(loaderUserInfo())

  //判断是否登录
  const isLogin = computed(() => !!token.value)

  //设置token
  function setToken(newToken) {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 设置用户信息
  function setUserInfo(newUserInfo) {
    try {
      userInfo.value = { ...initUserInfo, ...newUserInfo }
    } catch (error) {
      console.log(error)
    }
  }

  //退出登录
  function logout() {
    token.value = ''
    userInfo.value = initUserInfo
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
  return { userInfo, token, isLogin, logout, setToken, setUserInfo, }
})